import os
import sys
# DON'T CHANGE THIS !!!
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))

from flask import Flask, send_from_directory
from flask_cors import CORS
from src.models.models import db
from src.routes.user import user_bp
from src.routes.words import words_bp
from src.routes.practice import practice_bp
from src.routes.test import test_bp
from src.routes.report import report_bp
from src.routes.speech_mock import speech_mock_bp
from src.routes.ai_services import ai_bp
from src.routes.analytics import analytics_bp

app = Flask(__name__, static_folder=os.path.join(os.path.dirname(__file__), 'static'))
app.config['SECRET_KEY'] = 'asdf#FGSgvasgf$5$WGT'

# Enable CORS for all routes
CORS(app, origins="*")

# Register blueprints
app.register_blueprint(user_bp, url_prefix='/api')
app.register_blueprint(words_bp, url_prefix='/api')
app.register_blueprint(practice_bp, url_prefix='/api')
app.register_blueprint(test_bp, url_prefix='/api')
app.register_blueprint(report_bp, url_prefix='/api')
app.register_blueprint(speech_mock_bp, url_prefix='/api')
app.register_blueprint(ai_bp, url_prefix='/api')
app.register_blueprint(analytics_bp, url_prefix='/api')

# Database configuration
app.config['SQLALCHEMY_DATABASE_URI'] = f"sqlite:///{os.path.join(os.path.dirname(__file__), 'database', 'app.db')}"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)

# Initialize database and seed data
with app.app_context():
    db.create_all()
    
def seed_initial_data():
    """初始化基础数据"""
    from src.models.models import WordSet, Word, Example
    
    # 检查是否已有数据
    if WordSet.query.first():
        return
    
    # 创建词汇集
    word_set = WordSet(
        grade='6th',
        title='小学六年级词汇',
        source='PPE',
        size=20
    )
    db.session.add(word_set)
    db.session.flush()  # 获取ID
    
    # 添加示例单词
    sample_words = [
        {
            'en': 'boots',
            'zh': '靴子',
            'phonetic': '[buːts]',
            'image_url': 'https://images.unsplash.com/photo-1544966503-7cc5ac882d5f?w=300&h=200&fit=crop',
            'examples': [
                {'en': 'She put on her boots and went out.', 'zh': '她穿上靴子出去了。'},
                {'en': 'I need a new pair of boots.', 'zh': '我需要一双新靴子。'}
            ]
        },
        {
            'en': 'apple',
            'zh': '苹果',
            'phonetic': '[ˈæpl]',
            'image_url': 'https://images.unsplash.com/photo-1560806887-1e4cd0b6cbd6?w=300&h=200&fit=crop',
            'examples': [
                {'en': 'I eat an apple every day.', 'zh': '我每天吃一个苹果。'},
                {'en': 'The apple is red and sweet.', 'zh': '这个苹果又红又甜。'}
            ]
        },
        {
            'en': 'necessary',
            'zh': '必需的',
            'phonetic': '[ˈnesəsəri]',
            'examples': [
                {'en': 'Water is necessary for life.', 'zh': '水是生命必需的。'},
                {'en': 'It is necessary to study hard.', 'zh': '努力学习是必要的。'}
            ]
        },
        {
            'en': 'tomorrow',
            'zh': '明天',
            'phonetic': '[təˈmɒrəʊ]',
            'examples': [
                {'en': 'I will go to school tomorrow.', 'zh': '我明天要去学校。'},
                {'en': 'Tomorrow is a new day.', 'zh': '明天是新的一天。'}
            ]
        },
        {
            'en': 'convenient',
            'zh': '方便的',
            'phonetic': '[kənˈviːniənt]',
            'examples': [
                {'en': 'This shop is very convenient.', 'zh': '这家商店很方便。'},
                {'en': 'Online shopping is convenient.', 'zh': '网上购物很方便。'}
            ]
        }
    ]
    
    for word_data in sample_words:
        word = Word(
            set_id=word_set.id,
            en=word_data['en'],
            zh=word_data['zh'],
            phonetic=word_data.get('phonetic', ''),
            image_url=word_data.get('image_url', '')
        )
        db.session.add(word)
        db.session.flush()
        
        # 添加例句
        for ex_data in word_data.get('examples', []):
            example = Example(
                word_id=word.id,
                en_sentence=ex_data['en'],
                zh_sentence=ex_data['zh']
            )
            db.session.add(example)
    
    db.session.commit()

# Seed initial data
with app.app_context():
    seed_initial_data()

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serve(path):
    static_folder_path = app.static_folder
    if static_folder_path is None:
            return "Static folder not configured", 404

    if path != "" and os.path.exists(os.path.join(static_folder_path, path)):
        return send_from_directory(static_folder_path, path)
    else:
        index_path = os.path.join(static_folder_path, 'index.html')
        if os.path.exists(index_path):
            return send_from_directory(static_folder_path, 'index.html')
        else:
            return "index.html not found", 404

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

